package Server

import (
	"encoding/json"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

var clients = make(map[string]*websocket.Conn)  // connected clients
var connToID = make(map[*websocket.Conn]string) // map connections to user IDs
var broadcast = make(chan Message)              // broadcast channel

// Configure the upgrader
var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

type Message struct {
	Time string   `json:"time"`
	Data Userdata `json:"data"`
}
type Userdata struct {
	Email    string      `json:"email"`
	Username string      `json:"username"`
	UserId   string      `json:"UserId"`
	Message  string      `json:"message"`
	Shopid   json.Number `json:"Shopid"`
	From     json.Number `json:"From"`
}

func StartServer() {

	fs := http.FileServer(http.Dir("../public"))
	http.Handle("/", fs)

	// Configure websocket route
	http.HandleFunc("/ws", handleConnections)

	// Start listening for incoming chat messages
	go handleMessages()

	// Start the server on localhost port 8001 and log any errors
	log.Println("http server started on :8001")
	err := http.ListenAndServe(":8001", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
